package com.pingan.internal.point.shopping.common.utils;

import com.pingan.internal.point.shopping.common.exception.BusinessException;
import com.pingan.internal.point.shopping.common.msg.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * 文件上传工具包
 */
public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     *
     * @param file 文件
     * @return
     */
    public static void upload(MultipartFile file, String fullFileName){

        File dest = new File(fullFileName);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            //String str = Base64.getEncoder().encodeToString(file.getBytes());
            file.transferTo(dest);
            //return str;
        } catch (IllegalStateException e) {
            logger.error("上传图片异常：",e);
            throw new BusinessException(ErrorMessage.UPLOAD_ERROR);
        } catch (IOException e) {
            logger.error("上传图片IO异常：",e);
            throw new BusinessException(ErrorMessage.UPLOAD_ERROR);
        }
    }

    public static String upload(String  fileName, String fullFileName){

        File dest = new File(fullFileName);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        InputStream is = null;
        ByteArrayOutputStream byteStream =null;
        FileOutputStream fos = null;

        try {
            //保存文件
            File file = new File(fileName);
            is =new  FileInputStream(file);
            byteStream = new ByteArrayOutputStream();
            fos = new FileOutputStream(dest);
            byte[] b = new byte[1024];
            int len = 0;
            while((len=is.read(b)) !=-1){
                byteStream.write(b,0,len);
                fos.write(b,0,len);
            }
            String str = Base64.getEncoder().encodeToString(byteStream.toByteArray());
            return str;
        } catch (IllegalStateException e) {
            logger.error("上传图片异常：",e);
            throw new BusinessException(ErrorMessage.UPLOAD_ERROR);
        } catch (IOException e) {
            logger.error("上传图片IO异常：",e);
            throw new BusinessException(ErrorMessage.UPLOAD_ERROR);
        }finally {
            if(is !=null){
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            if(byteStream !=null){
                try {
                    byteStream.close();
                } catch (IOException e) {
                }
            }
            if(fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }

    }
}